package cc.taofoo.JUCTest;


/**
 * 由于 i ++ 过程中 Integer 引用发生了变化导致 synchronized 失效
 * 实际上 i++ ------> i = Integer.valueOf(i.intValue()+1);
 *
 * 解决：
 * synchronized(i) -----> synchronized(this)
 *
 */

public class BadLockOnInteger implements Runnable{

    private static Integer i=0;
    static BadLockOnInteger instance = new BadLockOnInteger();


    @Override
    public void run() {
        for(int j=0;j<1000;j++){
            synchronized (i){
                i++;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();t2.start();
        t1.join();t2.join();
        System.out.println(i);


    }


}


